package com.drugmanage.proxy;

import com.drugmanage.annotations.Pms;
import com.drugmanage.constant.DmConstant;
import com.drugmanage.exception.ParamsExcetion;
import com.drugmanage.service.IUserService;
import com.drugmanage.utils.AssertUtil;
import com.drugmanage.utils.LoginUserUtil;
import com.drugmanage.utils.ValidateUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 权限aop切面定义
 */
@Component
@Aspect
public class PerimissionProxy {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;
    @Resource
    private IUserService userService;

    @Before("execution(* com.*.controller.*.*(..))")
    public void before(JoinPoint joinPoint){
        /**
         * 获取方法的注解
         */
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Pms pms = method.getAnnotation(Pms.class);
        if(null!=pms){
            Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
            AssertUtil.Nologin(ValidateUtil.nullOrZeroInteger(userId),"用户未登录");
            AssertUtil.Nologin(userService.getById(userId)==null,"用户未登录");
            //获取session中的权限值
            List<String> permissions = (List<String>) session.getAttribute(DmConstant.USER_PERMISSION_KEY);
            if(!ValidateUtil.blankList(permissions)&&permissions.contains(pms.acl())){
                System.out.println("用户拥有操作权限");
                return ;
            }
            throw new ParamsExcetion("没有操作权限");
        }
    }
}
